﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TransCode.Entitys;
using System.ComponentModel;
using System.Windows.Threading;

namespace TransCode.Player.VideoPage
{
    /// <summary>
    /// Interaction logic for VideoPlayerControl.xaml
    /// </summary>
    public partial class VideoPlayerControl : UserControl, IVideoPlayer
    {
        DispatcherTimer timer = new DispatcherTimer();

        public VideoPlayerControl()
        {
            InitializeComponent();

            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(timer_Tick);

            playButton.mediaElement = this.mediaElement;
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (_video != null && playing && !mouseOver)
                progress.Value = mediaElement.Position.TotalSeconds / _video.NaturalDuration.TotalSeconds * 100;
        }

        Video _video = null;

        private void Element_MediaOpened(object sender, EventArgs e)
        {
            mediaElement.Play();
        }

        private void Element_MediaEnded(object sender, EventArgs e)
        {
            mediaElement.Stop();
        }



        public void Play(Video video)
        {
            _video = video;
            mediaElement.Source = new Uri(video.LocationPath + video.VideoName);
            mediaElement.Play();
            playing = true;
            timer.Start();
        }

        bool mouseOver = false;
        bool playing = false;

        public TimeSpan Position
        {
            get
            {
                return mediaElement.Position;
            }
            set
            {
                mediaElement.Position = value;
            }
        }

        private void progress_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            mediaElement.Position = TimeSpan.FromSeconds(_video.NaturalDuration.TotalSeconds / 100 * e.NewValue);
        }

        private void progress_MouseEnter(object sender, MouseEventArgs e)
        {
            mouseOver = true;
        }

        private void progress_MouseLeave(object sender, MouseEventArgs e)
        {
            mouseOver = false;
        }

        private void mediaElement_MouseEnter(object sender, MouseEventArgs e)
        {
            progressBorder.Visibility = System.Windows.Visibility.Visible;
        }

        private void mediaElement_MouseLeave(object sender, MouseEventArgs e)
        {
            progressBorder.Visibility = System.Windows.Visibility.Collapsed;
        }
    }
}
